<template>
	<view class="container">
		<view class="flex f-column f-align" v-if="isfetch">
			<view class="flex f-align f-justifyB blue-box">
				<view class="flex f-column font28 white">
					<text>订单编号：{{orderInfo.orderNumber}}</text>
					<text class="mt10">时　　间：{{orderInfo.transactionTime}}</text>
				</view>
				<text class="font32 white">数量X{{orderInfo.goodsNumber}}</text>
			</view>
			<view class="blue-line"></view>
			<view class="fixed-box">
				<view class="flex f-align f-justifyB mt20" v-for="item in orderInfo.orderDetails" :key="item.id"
					@click="$api.toPage('./orderStep?id=' + item.id)">
					<view class="flex f-align">
						<image :src="item.goodsUrl" style="width: 90rpx;height: 90rpx;"></image>
						<view class="flex f-column ml20">
							<view class="font28 gray333">
								{{item.goodName}}
							</view>
							<text class="font24 gray333 mt10">订单编号：{{item.shoeBuckleNumber || '未绑定'}}</text>
						</view>
					</view>
					<view class="flex f-align">
						<text class="font28 gray333">{{item.orderState}}</text>
						<text class="zlicon icon-right font28 gray333 ml10"></text>
					</view>
				</view>
			</view>
			<view class="detail-bottom flex f-align f-justifyB">
				<view class="btn font32 white f-center" @click="confirmHandle">重新结算</view>
				<view class="btn font32 white f-center" @click="printBarcode">打印条码</view>
				<view class="btn font32 white f-center" @click="openDoor">开门取衣</view>
			</view>
		</view>
	</view>
</template>

<script>
	import orderStep from './orderStep'
	// import {
	// 	inArray
	// } from '../utils/print.js'
	let util = require('../utils/util.js');
	export default {
		data() {
			return {
				orderInfo: {},
				isfetch: false,

				_discoveryStarted: false,
				devices: [],
				deviceId: '', // 模拟选择了一个打印机
				canWrite: false,
				_deviceId: '',
				_serviceId: '',
				_characteristicId: ''
			}
		},
		onLoad(option) {
			this.orderNumber = option.orderNumber
			this.openBluetoothAdapter()
		},
		onShow() {
			this.getDataList()
		},
		components: {
			orderStep
		},
		methods: {
			//发送数据
			sendStr: function(bufferstr, success, failed) {
				var that = this;
				wx.writeBLECharacteristicValue({
					deviceId: this._deviceId,
					serviceId: this._serviceId,
					characteristicId: this._characteristicId,
					value: bufferstr,
					success: function(res) {
						success(res);
						console.log('发送的数据：' + bufferstr)
						console.log('message发送成功')
					},
					failed: function(res) {
						fail(res)
						console.log("数据发送失败:" + JSON.stringify(res))
					},
					complete: function(res) {
						console.log("发送完成:" + JSON.stringify(res))
					}
				})
			},
			//遍历发送数据
			printInfo: function(arr) {
				var tthis = this;
				if (arr.length > 0) {
					this.sendStr(arr[0], function(success) {
						arr.shift();
						tthis.printInfo(arr);
					}, function(error) {
						console.log(error);
					});
				}
			},
			//打印条形码
			printBarcode() {
				if (!this.canWrite) {
					this.$api.msg('打印机连接异常, 请重新连接')
					return
				}
				
				let arrPrint = [];
				//初始化打印机
				arrPrint.push(util.sendDirective([0x1B, 0x40])); //16进制
				//居中对齐
				arrPrint.push(util.sendDirective([0x1B, 0x61, 0x01])); //16进制
				//正文
				//Enable the barcode
				arrPrint.push(util.sendDirective([0x1d, 0x45, 0x43, 0x01]));
				//Set the barcode height is 100
				arrPrint.push(util.sendDirective([0x1d, 0x68, 0xb4]));
				//Set HRI character print location on bottom
				// arrPrint.push(util.sendDirective([0x1d, 0x48, 0x02]));
				// arrPrint.push(util.sendDirective([0x1d, 0x77, 0x02]));
			
				//0x1d,0x6b,0x49,最后的14为条码内容的长度，"test1234567890".length
				arrPrint.push(util.sendDirective([0x1d, 0x6b, 0x49, 14]));
			
				//test1234567890条码内容，目前是指令方式打印，最大支持14位数字
				arrPrint.push(util.hexStringToBuff(this.orderInfo.orderNumber));
				// arrPrint.push(util.hexStringToBuff('1234567891231'));
				
				//恢复居左对齐
				arrPrint.push(util.sendDirective([0x1B, 0x61, 0x00])); //16进制
				
				arrPrint.push(util.hexStringToBuff(`用户昵称: ${this.orderInfo.userName}\n`));
				arrPrint.push(util.hexStringToBuff(`用户电话: ${this.orderInfo.userPhone}\n`));
				arrPrint.push(util.hexStringToBuff(`下单数量: ${this.orderInfo.goodsNumber}\n`));
				arrPrint.push(util.hexStringToBuff(`下单时间: ${this.orderInfo.transactionTime}\n`));
				arrPrint.push(util.hexStringToBuff(`下单地址: ${this.orderInfo.gzbhAddress}\n`));
				
				// arrPrint.push(util.hexStringToBuff(`用户昵称: 他化自在\n`));
				// arrPrint.push(util.hexStringToBuff(`用户电话: 18339112554\n`));
				// arrPrint.push(util.hexStringToBuff(`下单数量: 3\n`));
				// arrPrint.push(util.hexStringToBuff(`下单时间: 2022-09-06 12:12:12\n`));
				// arrPrint.push(util.hexStringToBuff(`下单地址: 未来路绿都广场\n`));
			
				arrPrint.push(util.sendDirective([0x1B, 0x64, 0x02])); 
			
				//发送数据
				this.printInfo(arrPrint);
			
			},
			//获取蓝牙设备所有服务(service)
			getBLEDeviceServices(deviceId) {
				wx.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						for (let i = 0; i < res.services.length; i++) {
							if (res.services[i].isPrimary) {
								this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
								return;
							}
						}
					},
					fail: (res) => {
						console.log("获取蓝牙服务失败：" + JSON.stringify(res))
					}
				});
			},

			//获取蓝牙设备某个服务中所有特征值(characteristic)
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				wx.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						console.log('getBLEDeviceCharacteristics success', res.characteristics)
						for (let i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							if (item.properties.read) {
								wx.readBLECharacteristicValue({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
								});
							}
							
							if (item.properties.write) {
								this.canWrite = true
								this._deviceId = deviceId;
								this._serviceId = serviceId;
								this._characteristicId = item.uuid;
							}
							
							if (item.properties.notify || item.properties.indicate) {
								wx.notifyBLECharacteristicValueChange({
									deviceId,
									serviceId,
									characteristicId: item.uuid,
									state: true,
								})
							}

						}
					},
					fail(res) {
						console.error('获取特征值失败：', res)
					}
				})

				// 操作之前先监听，保证第一时间获取数据
				// wx.onBLECharacteristicValueChange((characteristic) => {
				// 	const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
				// 	const data = {}
				// 	if (idx === -1) {
				// 		data[`chs[${this.data.chs.length}]`] = {
				// 			uuid: characteristic.characteristicId,
				// 			value: ab2hex(characteristic.value)
				// 		}
				// 	} else {
				// 		data[`chs[${idx}]`] = {
				// 			uuid: characteristic.characteristicId,
				// 			value: ab2hex(characteristic.value)
				// 		}
				// 	}
				// 	// data[`chs[${this.data.chs.length}]`] = {
				// 	//   uuid: characteristic.characteristicId,
				// 	//   value: ab2hex(characteristic.value)
				// 	// }
				// 	this.setData(data)
				// })
			},
			//连接低功耗蓝牙设备
			createBLEConnection(e) {
				var that = this;

				wx.createBLEConnection({
					deviceId: that.deviceId,
					success: (res) => {

						that.getBLEDeviceServices(that.deviceId);

						// setTimeout(function() {
						// 	//要延时1s
						// 	that.writeBLECharacteristicValue();

						// }, 1000) //延迟时间 这里是2秒
					},
					fail: (res) => {
						this.$api.msg('蓝牙连接失败')
						console.log("蓝牙连接失败:", res);
					}
				});
				that.stopBluetoothDevicesDiscovery();
			},
			// 停止
			stopBluetoothDevicesDiscovery() {
				wx.stopBluetoothDevicesDiscovery()
			},
			//寻找到新设备的事件的回调函数
			onBluetoothDeviceFound() {
				wx.onBluetoothDeviceFound((res) => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						if (this.deviceId) {
							return
						}
						if (device.name == 'Qsprinter' && device.localName == 'Qsprinter') {
							this.deviceId = device.deviceId
							this.createBLEConnection()
						}
						// const foundDevices = this.devices
						// const idx = inArray(foundDevices, 'deviceId', device.deviceId)
						// const data = {}
						// if (idx === -1) {
						// 	data[`devices[${foundDevices.length}]`] = device
						// } else {
						// 	data[`devices[${idx}]`] = device
						// }
						// this.setData(data)
					})
				})
			},
			//开始搜寻附近的蓝牙外围设备
			startBluetoothDevicesDiscovery() {
				if (this._discoveryStarted) {
					return
				}
				this._discoveryStarted = true
				wx.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					success: (res) => {
						console.log('startBluetoothDevicesDiscovery success', res)
						this.onBluetoothDeviceFound()

					},
					fail: (res) => {
						this.$api.msg('蓝牙初始化失败')
					}
				})
			},
			//初始化蓝牙模块
			openBluetoothAdapter() {
				wx.openBluetoothAdapter({
					success: (res) => {
						console.log('openBluetoothAdapter success', res)
						this.startBluetoothDevicesDiscovery()
					},
					fail: (res) => {
						console.log(res);
						if (res.errCode === 10001) {
							wx.onBluetoothAdapterStateChange(function(res) {
								console.log('onBluetoothAdapterStateChange', res)
								if (res.available) {
									this.startBluetoothDevicesDiscovery()
								}
							})
						}
					}
				})
			},
			openDoor() {
				uni.showLoading({
					title: '开门中...'
				})
				this.$http.ajax({
					url: '/Order/adminGetOut',
					params: {
						shoeBuckleNumber: this.orderInfo.orderNumber,
						adminId: uni.getStorageSync('adminId')
					}
				}).then((res) => {
					uni.hideLoading()
					this.$api.msg(res.msg)
					if (res.code == 200) {
						this.getDataList()
					}
				})
			},
			confirmHandle() {
				uni.navigateTo({
					url: '/pages/settleAgain?orderNumber=' + this.orderInfo.orderNumber
				})
			},
			getDataList() {
				this.$http.ajax({
					url: '/Order/list',
					params: {
						orderNumber: this.orderNumber
					}
				}).then((res) => {
					this.isfetch = true
					if (res.code == 0) {
						this.orderInfo = res.data[0]
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding: 42rpx 32rpx 0;
		padding-bottom: 90rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 90rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 90rpx);
		background-color: #FFFFFF;
		position: relative;

		.fixed-box {
			position: absolute;
			left: 52rpx;
			top: 220rpx;
			z-index: 99;
			background: linear-gradient(179deg, #8FB6FF 0%, #FFFFFF 100%);
			width: 646rpx;
			padding: 78rpx 20rpx;
		}

		.blue-box {
			width: 686rpx;
			height: 120rpx;
			background: #4082FD;
			border-radius: 20rpx;
			padding: 0 56rpx;
		}

		.blue-line {
			width: 686rpx;
			height: 32rpx;
			background: #4082FD;
			border-radius: 16rpx;
			margin-top: 42rpx;
		}

		.btn {
			width: 200rpx;
			height: 70rpx;
			background: #4082FD;
			border-radius: 36rpx;
			margin-top: 20rpx;
		}

		.s-btn {
			width: 200rpx;
			height: 70rpx;
			background: #4082FD;
			border-radius: 36rpx;
			margin: 20rpx 0 0;
		}

		.detail-bottom {
			width: 686rpx;
			height: 100rpx;
			border-top: 2rpx solid #EAEAEA;
			padding-left: 32rpx;
			padding-right: 32rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			position: fixed;
			right: 0;
			bottom: 0;
			background: #FFFFFF;
			box-sizing: content-box;
		}
	}
</style>
